class UsersController < ApplicationController
  require 'movistar_gateway'
  require 'hpricot'
  require 'copiagenda'
  
  before_filter :login_required, :only => [:send_sms, :update]
  
  # render new.rhtml
  def new
  end

  def create
    cookies.delete :auth_token
    # protects against session fixation attacks, wreaks havoc with 
    # request forgery protection.
    # uncomment at your own risk
    # reset_session
    @user = User.new(params[:user])
    @user.save
    if @user.errors.empty?
      self.current_user = @user
      redirect_to user_home_url
      flash[:notice] = "Ya estás registrado, sólo tienes que rellenar unos datitos más!"
    else
      render :action => 'new'
    end
  end
  
  def update
    @user = current_user
    return unless request.post?
    @user.update_attributes(params[:user])
    flash[:notice] = "actualizado con éxito"
    redirect_to user_home_url
  end
  
  
  
  def home
    @messages = current_user.messages.paginate :page => params[:page], :order => 'created_at DESC'
    @user = current_user
  end
  
  def complete_profile
    
  end
  
  def list_sms_ajax
  	@messages = current_user.messages.paginate :page => params[:page], :order => 'created_at DESC'

  	render :layout => false
  end
  
  def get_copiagenda
    begin
        cag = Copiagenda.new("#{params[:telcopiag]}", "#{params[:passcopiag]}")
        @contacts = cag.RetrieveContacts
    rescue
       @error = "Revisa tus datos de copiagenda, algo huele a podrido :)" 
    end
    render :layout => false
  end
  
  def send_sms
        gateway = MovistarGateway.new("#{current_user.mobile}", "#{current_user.mobile_pass}")
        gateway.send(current_user.mobile_mum, params[:sms])
        ip = request.env['HTTP_X_FORWARDED_FOR'] || request.env['HTTP_CLIENT_IP'] || request.env['REMOTE_ADDR']
	    Message.create({:message => params[:sms], :user_id => current_user.id, :mobile_mum => "#{current_user.mobile_mum}", :ip => "#{ip}"})
  end
end
